﻿


using InfluxDB.Client.Api.Domain;
using IotClientService.Models.Lg;
using IotClientService.Models.Lg.Remote;
using IotClientService.Services;
using IotContract.Enums;
using XT.Common.Extensions;

namespace IotClientService.Handles.lgs;
/// <summary>
/// 密封钉焊机 6201  7201 
/// </summary>
public class LgHandleSealNail:LgHandleBase
{
    public LgHandleSealNail(ILgApiService lgCallApiService) : base(lgCallApiService)
    {
    }

    /// <summary>
    /// 设备类型
    /// </summary>
    public override IotEquipType EquipType { get; set; } = IotEquipType.SEAL;
    /// <summary>
    /// 处理消息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public override async Task<bool> HandleMsg(LgMsgInfo msg)
    {
        string replyCmd = string.Empty;
        switch (msg.Command)
        {
            // 作业实处理Data报告
            case "901":
                replyCmd = "902";
              await  Handle901(msg, replyCmd);
                break;

            // 设备状态报告指示回应
            case "910":
              await  Handle910(msg, "910");
                // send 833 

                break;
            // 设备状态报告
            case "913":
              await  Handle913(msg, "913");

                break;
            // 作业mode报告
            case "917":
                replyCmd = "918";
              await  Handle917(msg, replyCmd);
                break;
            // 通信状态报告邀请
            case "925":
                replyCmd = "926";
              await  Handle925(msg, replyCmd);
                break;
            // 通信状态报告回应
            case "926":
              await  Handle926(msg, "926");
                break;
            // 电芯投入报告
            case "933":
                replyCmd = "934";
               await Handle933(msg, replyCmd);
                break;

            // 未知命令,错误
            case "981":
               await Handle981(msg, "981");
                break;
            // 设备Trouble报告
            case "985":
              await  Handle985(msg, "985");
                break;


            // 设置时间指示
            case "999":
              await  Handle999(msg, "999");
                break;
            default:
                // send 981,
              await  Handle981(msg, "981");
                break;
        }
        return true;
    }
    /// <summary>
    /// 作业实处理Data报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle901(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 电池数量
        var cellCount = msg.Message.Substring(18, 1).To<int>();
        List<LgCellNg> ngs = new List<LgCellNg>();

        List<LgSealNailResult> datas = new List<LgSealNailResult>();

        for (int i = 0; i < cellCount; i++)
        {
            // 结果数据 108*电池数量
            string result = msg.Message.Substring(19 +  108 * i, 108);
            if (string.IsNullOrWhiteSpace(result)) continue;
          
            ngs.Add(new LgCellNg
            {
                Cell = result.Substring(0, 24),
                Ng = result.Substring(24, 1).To<int>(),
                NgCode = result.Substring(25, 4)
            });


            LgSealNailResult lgSealNailResult = new LgSealNailResult
            {
                ChannelPosition = result.Substring(29, 1),
                DeviceFixture = result.Substring(30, 1),
                CleaningCcdResult = result.Substring(31, 1).To<int>(),
                NailCcdResult = result.Substring(32, 1),
                WeldingCcdResult = result.Substring(33, 1),
                WeldingDuration = result.Substring(34, 4).To<double>(),
                PostWeldingCcdResult = result.Substring(38, 1),
                LaserCleaningCount = result.Substring(39, 2).To<int>(),
                LaserCleaningPeakPower = result.Substring(41, 5).To<double>(),
                LaserCleaningFrequency = result.Substring(46, 4).To<int>(),
                LaserCleaningSpeed = result.Substring(50, 5).To<int>(),
                WeldingPeakPower = result.Substring(55, 4).To<double>(),
                WeldingEnergy = result.Substring(59, 5).To<double>(),
                WeldingFrequency = result.Substring(64, 3).To<int>(),
                WeldingPulseWidth = result.Substring(67, 1).To<int>(),
                WeldingDefocusAmount = result.Substring(68, 4).To<double>(),
                WeldingSpeed = result.Substring(72, 2).To<int>(),
                WeldingShieldingGasFlow = result.Substring(74, 5).To<double>(),
                InLightSignalResult = result.Substring(79, 1).To<int>(),
                StepStartTime = result.Substring(80, 14),
                StepEndTime = result.Substring(94, 14)
            };
            datas.Add(lgSealNailResult);
        }

        var rep= await Api.CommitSealNailResult(new Models.Lg.Remote.LgSealNailResultRequest
        {
            EquipNum=Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Ngs = ngs,
            Datas = datas
        });
        if (!rep.Success)
        {
            Equip.ExMessage = rep.Message;
            msg.Body ="1";
            await Handle981(msg, "981");
            return;
        }
      
        // 数量
        var count = ngs.Count();
        string ngStr = string.Empty;
        if (rep.Result.IsNotNull())
        {
            foreach (var cell in rep.Result)
            {
                ngStr += $"{cell.ToString()}";
            }
        }


        sendMsg.Body = $"{count}{ngStr}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);


    }


   
    /// <summary>
    /// 电芯投入报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle933(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // cell数量
        var cellCount = msg.Message.Substring(18, 1).To<int>();

       
        List<LgOcvCellInfo> cells = new List<LgOcvCellInfo>();
        for(int i=0;i<cellCount; i++)
        {
            var str = msg.Message.Substring(19 + i * 25, 25);
            cells.Add(new LgOcvCellInfo
            {
                Cell = str.Substring(0, 24),
                // str.Substring(24, 1)
                Channel = str.Substring(24, 1)
            });
        }

        var result= await Api.CommitSealNailEnter(new LgSealNailEnterCellRequest
        {
            Cells=cells,
            EquipNum=Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType
        });
       
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            msg.Body = "1";
            await Handle981(msg, "981");
            return;
        }
        Equip.Remark = $"cell load:{cellCount}";

        #region 传输body
        string all = cells.Count.ToString();
        int count = result.Result?.Ngs?.Count ?? 0;

        if (count != cells.Count)
        {
            all = "1";
        }
        else
        {
            for (int i = 0; i < cells.Count; i++)
            {
                var cell = cells[i];
                var ng = result.Result.Ngs[i];
                var judge = result.Result.CellJudges[i];
                all += $"{cell.Cell.PadRight(24, '0')}{ng.Ng}{ng.NgCode}{judge.ToString()}";
            }

        }


        #endregion
        sendMsg.Body = all;
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }

    


   
}
